<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCurrentUserStore } from '@/modules/security/stores/currentUserStores'
import { webSocketStore } from '@/modules/socket/stores/webSocket'
import { securityApi } from '@/modules/security/api'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useCurrentUserStore()
const wsStore = webSocketStore()

// 消息计数
const messageCount = ref(0)

// 计算属性：用户信息
const userInfo = computed(() => userStore.currentUser?.user)
const userRoles = computed(() => userStore.currentUser?.roles || [])

// 计算属性：WebSocket 状态
const wsStatus = computed(() => ({
  connected: wsStore.session?.wsConnected || false,
  statusText: wsStore.session?.wsConnected ? '已连接' : '未连接',
  statusType: wsStore.session?.wsConnected ? 'success' : 'danger'
}))

// 处理登出
const handleLogout = async () => {
    await securityApi.logout()
    // 断开 WebSocket 连接
    wsStore.disconnectWebSocket()
    userStore.clearUser()
    await router.push('/login')
    ElMessage.success('登出成功')
}

// 处理 WebSocket 重连
const handleReconnect = () => {
  if (!wsStatus.value.connected) {
    wsStore.reconnectWebSocket()
    ElMessage.info('正在重新连接...')
  }
}

// 监听 WebSocket 消息
const handleWsMessage = (message: string) => {
  messageCount.value++
  ElMessage.info({
    message: `收到新消息: ${message}`,
    duration: 2000
  })
}

onMounted(() => {
  // 订阅消息
  wsStore.subMessage('/admin/home', handleWsMessage)
  
  // 如果未连接，尝试连接
  if (!wsStore.session?.wsConnected) {
    wsStore.connectWebSocket()
  }
})

onUnmounted(() => {
  // 取消订阅
  wsStore.unSubMessage('/admin/home')
})
</script>

<template>
  <el-row class="status h">
    <el-col :span="8" class="h">
        <el-avatar
          :size="32"
          src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
        />
    </el-col>
    <el-col :span="8" class="h">
      <!-- 用户信息 -->
      <el-dropdown trigger="click" class="h">
        <span>{{ userInfo?.username }}</span>
        <template #dropdown>
          <el-dropdown-menu>
            <!-- 角色信息 -->
            <el-dropdown-item disabled>
              <div class="roles-info">
                <div class="title">角色列表：</div>
                <div
                  v-for="role in userRoles"
                  :key="role.id"
                  class="role-item"
                >
                  {{ role.name }}
                </div>
              </div>
            </el-dropdown-item>
            <el-dropdown-item divided @click="handleLogout">
              退出登录
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </el-col>
    <el-col :span="8" class="item h">
      <!-- WebSocket 状态 -->
      <div class="h" @click="handleReconnect">
        <el-tag
          :type="wsStatus.statusType"
          size="small"
          :class="{ clickable: !wsStatus.connected }"
        >
          {{ wsStatus.statusText }}
          <template v-if="wsStatus.connected && messageCount > 0">
            ({{ messageCount }})
          </template>
        </el-tag>
      </div>
    </el-col>
  </el-row>
</template>

<style scoped lang="scss">
.status{
  align-items: center;
  justify-items: center;
}
.h{
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>